package com.leyou.search.service.impl;

import com.leyou.common.dto.PageDTO;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.search.entity.Goods;
import com.leyou.search.entity.SearchParamDTO;
import com.leyou.search.repository.GoodRepository;
import com.leyou.search.service.SearchService;
import com.leyou.starter.elastic.dto.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.stream.Collectors;

import static com.leyou.search.constants.SearchConstants.*;

@Slf4j
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private GoodRepository repository;

    @Autowired
    private ItemClient itemClient;

    @Override
    public void createIndexAndMapping() {
        try {
            log.info("尝试删除存在的索引库");
            repository.deleteIndex();
        } catch (Exception e) {
            log.warn("索引库不存在，无需删除");
        }
        //创建索索引库和映射
        log.info("尝试创建索引库");
        repository.createIndex(SOURCE_TEMPLATE);

    }

    @Override
    public void loadData() {
        int page =1, rows = 10;

        while (true) {
            log.info("开始导入第{}页数据",page);
            //查询商品spu
            PageDTO<SpuDTO> info = itemClient.querySpuByPage(page, rows, true, null, null, null);
            List<SpuDTO> spuList = info.getItems();
            //把spu数据封装到goods
//  1.      List<Goods>goodsList = new ArrayList<>();
//        for (SpuDTO spuDTO : spuList) {
//            Goods goods = buildGoods(spuDTO);
//            goodsList.add(goods);
//        }
//   2.     List<Goods> goodsList = spuList.stream().map(spuDTO -> buildGoods(spuDTO)).collect(Collectors.toList());
            List<Goods> goodsList = spuList.stream().map(this::buildGoods).collect(Collectors.toList());
            //写入elasticsearch
            repository.saveAll(goodsList);
            log.info("导入第{}页数据成功");
            page++;
            if (page>info.getTotalPage()){
                //最后一页
                break;
            }
            //翻页
        }
        log.info("全部数据导入成功，共{}页",page);
    }

    @Override
    public Mono<List<String>> getSuggestion(String keyPrefix) {
        return repository.suggestBySingleField(SUGGEST_FIELD,keyPrefix);
    }

    @Override
    public Mono<PageInfo<Goods>> searchGoodList(SearchParamDTO paramDTO) {
        //构建搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        //过滤
        sourceBuilder.fetchSource(INCLUDES_SOURCE,EMPTY_SOURCE);
        //query查询
        String key = paramDTO.getKey();
        if (StringUtils.isBlank(key)){
            throw new LyException(404,"没有找到与“”相关的商品");
        }
      sourceBuilder.query(QueryBuilders.boolQuery()
      .must(QueryBuilders.matchQuery(SEARCH_FIELD,key)));
        //排序
        String sortBy = paramDTO.getSortBy();
        if (StringUtils.isNotBlank(sortBy)){
            //需要排序
            sourceBuilder.sort(sortBy,paramDTO.getDesc() ? SortOrder.DESC :SortOrder.ASC);
        }
        //分页
        sourceBuilder.from(paramDTO.getFrom()).size(paramDTO.getSize());
        //高亮
        sourceBuilder.highlighter(new HighlightBuilder().field(HIGHLIGHT_FIELD)
                .preTags(PRE_TAG).postTags(POST_TAG));

        return repository.queryBySourceBuilderForPageHighlight(sourceBuilder);
    }

    @Override
    public void saveItemSpuId(Long spuId) {
        //查询spu
        SpuDTO spu = itemClient.queryGoodsById(spuId);
        //构建goods
        Goods goods = buildGoods(spu);
        //新增goods
        repository.save(goods);
    }

    @Override
    public void deleteItemSpuId(Long spuId) {
        repository.deleteById(spuId);
    }

    private Goods buildGoods(SpuDTO spuDTO) {
        //1.商品标题，原有标题基础上，拼接分类名称。品牌名称
        String title = spuDTO.getTitle()+spuDTO.getCategoryName()+spuDTO.getBrandName();
        //2。suggestion：自动补全字段，包含：商品名称、分类名称、品牌名称
        Set<String>suggestion =new HashSet<>();
        suggestion.add(spuDTO.getName());
        suggestion.add(spuDTO.getBrandName());
        Collections.addAll(suggestion,spuDTO.getCategoryName().split("/"));

        //3。规格参数specs List<Map<String,Object>>
        //key是name和value，name的值是规格参数名称，value的值是规格参数的值
        List<SpecParamDTO> list = itemClient.querySpecsValues(spuDTO.getId(), true);
        //准备specs集合
        List<Map<String,Object>>specs = new ArrayList<>(list.size());
        //把specsParamDTO变为一个Map<String,Object>
        for (SpecParamDTO paramDTO : list) {
            Map<String,Object>map =new HashMap<>(2);
            map.put("name",paramDTO.getName());
            map.put("value",paramDTO.getValue());
            specs.add(map);
        }
        //sku相关数据，包括：图片、价格、销量
        List<SkuDTO> skuList = spuDTO.getSkus();
        if (CollectionUtils.isEmpty(skuList)){
            skuList= itemClient.querySkuBySpuId(spuDTO.getId());
        }
        //销量
        long sold =0L;
        Set<Long>prices=new HashSet<>();
        for (SkuDTO skuDTO : skuList) {
            sold +=skuDTO.getSold();
            prices.add(skuDTO.getPrice());
        }
        //图片，取一张即可
        String image = StringUtils.substringBefore(skuList.get(0).getImages(), ",");
        //封装goods
        Goods goods = new Goods();
        goods.setUpdateTime(new Date());
        goods.setTitle(spuDTO.getTitle());
        goods.setSuggestion(suggestion);
        goods.setSpecs(specs);
        goods.setSold(sold);
        goods.setPrices(prices);
        goods.setImage(image);
        goods.setId(spuDTO.getId());
        goods.setCategoryId(spuDTO.getCid3());
        goods.setBrandId(spuDTO.getBrandId());
        return goods;
    }
}
